package main

import (
	"context"
	wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
	"io/ioutil"
	"os"
	"path/filepath"
)

// App struct
type App struct {
	ctx context.Context
}

// NewApp creates a new App application struct
func NewApp() *App {
	return &App{}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx
}

func (a *App) LoadTreeNodes(path string) ([]TreeData, error) {
	fileInfos, err := ioutil.ReadDir(path)
	if err != nil {
		wailsRuntime.LogError(a.ctx, err.Error())
		return nil, err
	}
	children := make([]TreeData, 0)
	for _, info := range fileInfos {
		fileName := info.Name()
		filePath := path + string(filepath.Separator) + fileName
		treeData := TreeData{Title: fileName, Key: filePath, IsLeaf: true}
		if info.IsDir() {
			treeData.IsLeaf = false
			if subFiles, innerErr := ioutil.ReadDir(filePath); innerErr == nil && len(subFiles) > 0 {
				treeData.Children = make([]TreeData, 0)
			}
		}
		children = append(children, treeData)
	}

	return children, err
}

type FileContent struct {
	Path  string `json:"path"`
	Value string `json:"value"`
}

func (a *App) ReadFileContent(path string) (FileContent, error) {
	fileContent := FileContent{path, ""}
	lstat, err := os.Lstat(path)
	if err != nil {
		wailsRuntime.LogError(a.ctx, err.Error())
		return fileContent, err
	}
	if lstat.IsDir() {
		return fileContent, nil
	}

	file, err := os.ReadFile(path)
	if err != nil {
		wailsRuntime.LogError(a.ctx, err.Error())
		return fileContent, err
	}
	fileContent.Value = string(file)
	return fileContent, err
}

func (a *App) SaveFileContent(value string, path string) error {
	lstat, err := os.Lstat(path)
	if err != nil {
		wailsRuntime.LogError(a.ctx, err.Error())
		return err
	}
	if lstat.IsDir() {
		return nil
	}
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC, 0666)
	defer func(f *os.File) {
		err := f.Close()
		if err != nil {
			wailsRuntime.LogError(a.ctx, err.Error())
			return
		}
	}(f)
	_, err = f.WriteString(value)
	if err != nil {
		wailsRuntime.LogError(a.ctx, err.Error())
	}
	return err
}
